//
//  YUYALoginViewController.m
//  com.yigu.yuya
//
//  Created by hxp on 16/3/2.
//  Copyright © 2016年 hxp. All rights reserved.
//

#import "YAYILoginViewController.h"
#import "YAYIRegisterViewController.h"
#import "YAYINavigationController.h"
#import "YAYIEidtPersonalInfoViewController.h"

#import "YAYIUserinfoModel.h"


@interface YAYILoginViewController ()<UITextFieldDelegate, NSXMLParserDelegate, UITextFieldDelegate>

@property (strong,nonatomic)UIButton *cancelBtn;
@property (strong,nonatomic)UIImageView *topView;
@property (strong,nonatomic)UIImageView *iconImageView;
@property (strong,nonatomic)UITextField *accountTextField;
@property (strong,nonatomic)UITextField *passwordTextField;
@property (strong,nonatomic)UIButton *loginBtn;
@property (strong,nonatomic)UIButton *lostPasswordBtn;
@property (strong,nonatomic)UIButton *registerBtn;
@property (strong,nonatomic)UILabel  *leftLine;
@property (strong,nonatomic)UILabel  *otherLabel;
@property (strong,nonatomic)UILabel  *rightLine;
@property (strong,nonatomic)UIButton *qqLoginBtn;
@property (strong,nonatomic)UIButton *wxLoginBtn;
@property (strong,nonatomic)UIButton *weiboLoginBtn;
@property (strong,nonatomic)UILabel  *textFieldBackground;
@property (strong,nonatomic)UILabel *seprateLine;

@end

@implementation YAYILoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.view.backgroundColor = [UIColor  whiteColor];
    
    [self  setupSubView];
    [self loadDefaultHead];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewDidDisappear:(BOOL)animated
{

    self.passwordTextField.text = nil;
}


-(void)setupSubView{
    
    if (self.topView == nil) {
        self.topView = [UIImageView new];
        self.topView.image = [UIImage imageNamed:@"navagation_bg"];
        [self.view addSubview:self.topView];
    }
    [self.topView  mas_makeConstraints:^(MASConstraintMaker *make) {
          make.centerX.equalTo(self.view);
          make.width.equalTo(self.view);
          make.height.mas_equalTo(@(185 * YAYIScreenScale));
    }];
    
    
    if (self.cancelBtn == nil) {
        self.cancelBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [self.cancelBtn setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
        self.cancelBtn.titleLabel.font = [UIFont  systemFontOfSize:16 weight:0];
        [self.cancelBtn addTarget:self action:@selector(cancelActin:) forControlEvents:UIControlEventTouchUpInside];
        [self.view  addSubview:self.cancelBtn];
    }
    [self.cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@5);
        make.top.mas_equalTo(@30);
        make.size.mas_equalTo(CGSizeMake(60, 40));
    }];
    
    if (self.iconImageView == nil) {
        self.iconImageView =[UIImageView new];
        self.iconImageView.layer.masksToBounds = YES;
        self.iconImageView.backgroundColor = [UIColor grayColor];
        self.iconImageView.image = [UIImage imageNamed:@"default_head"];
        [self.view addSubview:self.iconImageView];
    }
    [self.iconImageView  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.topView);
//        make.centerY.equalTo(self.topView);
        make.top.equalTo(self.cancelBtn.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(90, 90));
        self.iconImageView.layer.cornerRadius = 45;
    }];
    
    // 背景
    if (self.textFieldBackground == nil) {
        self.textFieldBackground = [UILabel new];
        self.textFieldBackground.layer.borderColor = [UIColor lightGrayColor].CGColor;
        self.textFieldBackground.layer.borderWidth = 0.5;
        self.textFieldBackground.layer.masksToBounds = YES;
        self.textFieldBackground.layer.cornerRadius = 2;
        [self.view addSubview:self.textFieldBackground];
    }
    [self.textFieldBackground mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leftMargin.equalTo(@17);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.topView.mas_bottom).with.offset(31);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - 17 * 2, 88));
    }];
    
    if (self.accountTextField == nil) {
        self.accountTextField = [UITextField new];
        self.accountTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.accountTextField.borderStyle = UITextBorderStyleNone;
        self.accountTextField.font = [UIFont systemFontOfSize:14];
        self.accountTextField.layer.borderColor = [UIColor  lightGrayColor].CGColor;
        self.accountTextField.placeholder = @"手机号";
        self.accountTextField.tag = 0;
        self.accountTextField.delegate = self;
        [self.view addSubview:self.accountTextField];
    }
    [self.accountTextField  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@35);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.textFieldBackground.mas_top).with.offset(2);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - 35 * 2, 40));
    }];
    
    
    if (self.seprateLine == nil) {
        self.seprateLine = [UILabel  new];
        self.seprateLine.backgroundColor = [UIColor lightGrayColor];
        [self.view addSubview:self.seprateLine];
        
    }
    [self.seprateLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leftMargin.equalTo(@17);
        make.centerY.mas_equalTo(self.textFieldBackground);
        make.size.mas_equalTo(CGSizeMake(SCREEN_width - 25 * 2, 0.5));
    }];
    
    
    if (self.passwordTextField == nil) {
        self.passwordTextField = [UITextField  new];
        self.passwordTextField.placeholder = @"输入密码";
        self.passwordTextField.borderStyle = UITextBorderStyleNone;
        self.passwordTextField.delegate = self;
        self.passwordTextField.font = [UIFont systemFontOfSize:14];
        self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        self.passwordTextField.layer.borderColor = [UIColor  lightGrayColor].CGColor;
        self.passwordTextField.returnKeyType = UIReturnKeyGo;
        self.passwordTextField.delegate = self;
        self.passwordTextField.tag = 1;
        self.passwordTextField.secureTextEntry = YES;
        [self.view  addSubview:self.passwordTextField];
    }
    [self.passwordTextField  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leftMargin.mas_equalTo(self.accountTextField);
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.seprateLine.mas_bottom).with.offset(2);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - 35 * 2, 40));
        
    }];
    
    if (self.loginBtn == nil) {
        self.loginBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.loginBtn setBackgroundImage: [UIImage  imageNamed:@"button_normal"] forState:UIControlStateNormal];
        [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [self.loginBtn setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
        [self.loginBtn  addTarget:self action:@selector(loginAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.loginBtn];
    }
    [self.loginBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.passwordTextField.mas_bottom).with.offset(25);
        make.centerX.equalTo(self.view);
        make.leftMargin.equalTo(@17);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - 17 * 2, 44));
    }];
    
    if (self.lostPasswordBtn == nil) {
        self.lostPasswordBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.lostPasswordBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
        self.lostPasswordBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.lostPasswordBtn  setTitleColor:[UIColor  grayColor] forState:UIControlStateNormal];
        [self.lostPasswordBtn  addTarget:self action:@selector(lostPasswordAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view  addSubview:self.lostPasswordBtn];
    }
    [self.lostPasswordBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
          make.top.mas_equalTo(self.loginBtn.mas_bottom).with.offset(18);
          make.left.equalTo(@0);
          make.size.mas_equalTo(CGSizeMake(100, 10));
    }];
    
    
    if (self.registerBtn == nil) {
        self.registerBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        self.registerBtn.titleLabel.font = [UIFont systemFontOfSize:13];
        [self.registerBtn  setTitleColor:[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1] forState:UIControlStateNormal];
        [self.registerBtn  addTarget:self action:@selector(registerAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.view  addSubview:self.registerBtn];
    };
    [self.registerBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.lostPasswordBtn.mas_top);
        make.right.equalTo(@0);
        make.size.mas_equalTo(CGSizeMake(75, 10));
    }];
    
    
    
    // 第三方登录
    if (self.otherLabel == nil) {
        self.otherLabel = [UILabel  new];
        self.otherLabel.text = @"或使用以下方式直接点击登陆";
//        self.otherLabel.font = [UIFont systemFontOfSize:13];
        self.otherLabel.textColor =[UIColor  colorWithRed:83/255.0 green:165/255.0 blue:243/255.0 alpha:1];
       
        self.otherLabel.adjustsFontSizeToFitWidth = true;
        self.otherLabel.textAlignment = NSTextAlignmentCenter;
        [self.view  addSubview:self.otherLabel];
        self.otherLabel.hidden = YES;
    }
    [self.otherLabel  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.lostPasswordBtn.mas_bottom).with.offset(82.5 * YAYIScreenScale - 10 /2.0);
        make.size.mas_equalTo(CGSizeMake(self.view.frame.size.width - (28 + 64)*2, 10));
    }];
    
    if (self.leftLine == nil) {
        self.leftLine = [UILabel  new];
        self.leftLine.backgroundColor = [UIColor  lightGrayColor];
        [self.view  addSubview:self.leftLine];
        self.leftLine.hidden = YES;
    }
    [self.leftLine  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@28);
        make.top.mas_equalTo(self.lostPasswordBtn.mas_bottom).with.offset(82.5);
        make.size.mas_equalTo(CGSizeMake(62, 1));
    }];
    
    if (self.rightLine == nil) {
        self.rightLine = [UILabel new];
        self.rightLine.backgroundColor = [UIColor  lightGrayColor];
        [self.view addSubview:self.rightLine];
        self.rightLine.hidden = YES;
    }
    [self.rightLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.otherLabel);
        make.right.equalTo(@(-28));
        make.size.mas_equalTo(CGSizeMake(62, 1));
    }];
    
    
    if (self.qqLoginBtn == nil) {
        self.qqLoginBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.qqLoginBtn setBackgroundImage:[UIImage  imageNamed:@"qq_login_icon"] forState:UIControlStateNormal];
        [self.view addSubview:self.qqLoginBtn];
        self.qqLoginBtn.hidden = YES;
    }
    [self.qqLoginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.leftLine.mas_bottom).with.offset(44);
        make.left.equalTo(@(167/2.0));
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    if (self.wxLoginBtn == nil) {
        self.wxLoginBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.wxLoginBtn setBackgroundImage:[UIImage  imageNamed:@"wx_login_icon"] forState:UIControlStateNormal];
        [self.view addSubview:self.wxLoginBtn];
        self.wxLoginBtn.hidden = YES;
    }
    [self.wxLoginBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.mas_equalTo(self.qqLoginBtn);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
    if (self.weiboLoginBtn == nil) {
        self.weiboLoginBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        [self.weiboLoginBtn setBackgroundImage:[UIImage  imageNamed:@"sina_wb_login_icon"] forState:UIControlStateNormal];
        [self.view addSubview:self.weiboLoginBtn];
        self.weiboLoginBtn.hidden = YES;
    }
    [self.weiboLoginBtn  mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.qqLoginBtn.mas_top);
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.right.equalTo(@(-167/2.0));
    }];
}


/**
 *  默认头像
 */
-(void)loadDefaultHead
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    if ([user valueForKey:YAYIUsernameKey] != nil) {
        self.accountTextField.text = [user valueForKey:YAYIUsernameKey];

        NSString *urlStr = [user valueForKey:YAYIHeadKey];
        if (urlStr) {
            
            [self.iconImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"default_head"]];
            
        }
        
    }else{
        [self.iconImageView sd_setImageWithURL:nil placeholderImage:[UIImage imageNamed:@"default_head"] completed:nil];
    }
}


/**
 * 取消登陆
 */
-(void)cancelActin:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (self.cancelOperation) {
        self.cancelOperation();
    }
}


#pragma mark - 获取数据
/** 用户登录
 *
 */
-(void)userLlogin{
    
    if (self.accountTextField.text == 0) {
        [SVProgressHUD showImage:nil status:@"\n\n手机号不能为空\n\n"];
        return;
    }
    if (self.passwordTextField.text.length == 0) {
        [SVProgressHUD showImage:nil status:@"\n\n密码不能为空\n\n"];
        return;
    }
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *versionStr = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"mobile"] = self.accountTextField.text;
    param[@"password"] = self.passwordTextField.text;
//    param[@"deviceid"] = [CloudPushSDK getDeviceId];
    param[@"systemid"] = @"2";
    param[@"versions"] = versionStr;
    param[@"role"] = @(2);
    
    YAYILog(@"param:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:userLogin_url APIStr:API param:param finish:^(NSData *data, NSDictionary *dict, NSError *error, NSDictionary *responseError) {
        
        if (error == nil) {

            YAYILog(@"返回：%@", dict);

            if ([dict[@"status"] isEqualToString:@"success"]) {

                // 即时聊天登录

                // 存账号密码
                NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
                [userdef setValue:self.accountTextField.text forKey:YAYIUsernameKey];
                [userdef setValue:self.passwordTextField.text forKey:YAYIPasswordKey];
                [userdef synchronize];

                NSHTTPCookieStorage *cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
                for (int i = 0;  i < cookieJar.cookies.count; i ++) {
                    
                    NSHTTPCookie *cookie = [cookieJar cookies][i];
                    if (i == cookieJar.cookies.count - 1) {

                        [userdef setValue:cookie.value forKey:YAYILoginCookieKey];
                        [userdef synchronize];
                    }
                }

                // 登录状态改变
                [self getUserInfo];
//                [YAYILoginViewController loginStateChanged:YAYILoginStateLogin];
//                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else{
                
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
            }
        }else{
            
            NSString *erroMsg = [NSString stringWithFormat:@"%@", error];
            NSRange range = [erroMsg rangeOfString:@"网络错位"];
            if (range.location != NSNotFound) {
                
                [SVProgressHUD showImage:nil status:@"\n\n网络错误\n\n"];
            }else{
            
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:error.userInfo[@"com.alamofire.serialization.response.error.data"] options:NSJSONReadingMutableContainers error:nil];
                YAYILog(@"dict:%@", dict);
                
                [SVProgressHUD showImage:nil status:[NSString stringWithFormat:@"\n\n%@\n\n", dict[@"message"]]];
            }
        }
    }];
}


- (void)getUserInfo
{

    [YAYINetWorking getWithURL:me_personalinfo param:nil finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            
            YAYILog(@"返回：%@", dict);
            
            // 判断是否填写个人信息
            NSString *fullname = dict[@"data"][@"fullname"];
            NSString *title = dict[@"data"][@"title"];
            if (fullname && ![title isKindOfClass:[NSNull class]] && fullname.length > 0 &&
                title && ![title isKindOfClass:[NSNull class]]) { // 已填写个人信息
                
                YAYIUserinfoModel *userInfoModel = [[YAYIUserinfoModel alloc] init];
                [userInfoModel setValuesForKeysWithDictionary:dict[@"data"]];
                
                // 保存认证信息
                // 认证标志(0、未提交，1、待处理，2、已认证，3、认证失败)
                NSInteger verifyState = [dict[@"data"][@"v"] integerValue];
                NSUserDefaults *userdef = [NSUserDefaults  standardUserDefaults];
                [userdef setValue:userInfoModel.fullname forKey:YAYIDoctorNameKey];
                [userdef setInteger:userInfoModel.id forKey:YAYIUserIDKey];
                [userdef setValue:userInfoModel.avatar forKey:YAYIDoctorAvatarKey];
                
                [userdef setInteger:verifyState forKey:YAYIVerifyState];
                [userdef synchronize];
                
                [YAYILoginViewController loginStateChanged:YAYILoginStateLogin userInfoModel:userInfoModel];
                
                if (self.loginSuccessOperation) {
                    self.loginSuccessOperation();
                }

                [self dismissViewControllerAnimated:YES completion:nil];
            }else{ // 没有填写个人信息
            
                [SVProgressHUD showImage:nil status:@"\n\n请完善个人信息\n\n"];
                
                if (self.loginSuccessOperation) {
                    self.loginSuccessOperation();
                }
                
                // 跳转到填写个人信息页
                YAYIEidtPersonalInfoViewController *ctl = [[YAYIEidtPersonalInfoViewController alloc] init];
                [self.navigationController pushViewController:ctl animated:YES];
            }
        }
    }];
}


#pragma mark - 响应事件
/**
 * 忘记密码
 */
-(void)lostPasswordAction:(UIButton *)sender
{
    YAYIRegisterViewController *registerView = [YAYIRegisterViewController new];
//    UINavigationController *nav = [[UINavigationController  alloc] initWithRootViewController:registerView];
    registerView.titleStr = @"密码重置";
//    [self presentViewController:nav animated:NO completion:nil];
     [self.navigationController pushViewController:registerView animated:YES];

}
/**
 * 注册
 */
-(void)registerAction:(UIButton *)sender
{
    YAYIRegisterViewController *registerView = [YAYIRegisterViewController new];
    registerView.titleStr = @"注册";
//    [self presentViewController:nav animated:YES completion:nil];
    [self.navigationController pushViewController:registerView animated:YES];
}


/**
 * 登陆
 */
-(void)loginAction:(UIButton *)sender
{
    [self userLlogin];
    
}


#pragma mark  - 工具方法
/**
 *  获取设备号
 */

//-(void)createMsgHud:(NSString *)msg{
//    YAYIHudProgressView *hud = [[YAYIHudProgressView alloc] initWithView:self.view];
//    [self.view addSubview:hud];
//    [hud setMessage:msg];
//    
//    [hud removeFromSuperview:YES time:1 isHinden:YES];
//}


#pragma mark - 代理方
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (0 == textField.tag) {
        
        [textField  resignFirstResponder];
        [self.passwordTextField becomeFirstResponder];
        
    }else if (1 == textField.tag) {
        
        [textField  resignFirstResponder];
        [self userLlogin];
    }
    
    
    return YES;
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (0 == textField.tag) {

        self.iconImageView.image = [UIImage imageNamed:@"default_head"];
    }
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    
    if (0 == textField.tag) {
        
        self.iconImageView.image = [UIImage imageNamed:@"default_head"];
    }
    return YES;
}


#pragma mark - 外部调用
+ (void)loginStateChanged:(YAYILoginState)state userInfoModel:(YAYIUserinfoModel *)userInfoModel
{
    // 发送通知
    NSNotification *not = [NSNotification notificationWithName:YAYILoginNotifyName object:userInfoModel];
    [[NSNotificationCenter defaultCenter] postNotification:not];
}


+ (void)loginStateChanged:(YAYILoginState)state
{
    // 发送通知
    NSNotification *not = [NSNotification notificationWithName:YAYILoginNotifyName object:nil];
    [[NSNotificationCenter defaultCenter] postNotification:not];
}


@end
